package org.example.laboratorymanagement.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.laboratorymanagement.pojo.Device;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Result;
import org.example.laboratorymanagement.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/devices")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除设备ids：{}",ids);
        deviceService.delete(ids);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Device device){
        log.info("修改设备信息：{}",device);
        deviceService.update(device);
        return Result.success();
    }

    @PostMapping
    public Result insert(@RequestBody Device device){
        log.info("添加设备：{}",device);
        deviceService.insert(device);
        return Result.success();
    }

    @GetMapping
    public Result pageDevices(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              String name, String local){
        log.info("分页查询实验室设备，参数：{},{},{},{}",page, pageSize, name, local);
        PageBean pageBean = deviceService.pageDevices(page, pageSize, name, local);
        return Result.success(pageBean);
    }

    @PostMapping("/insertBatch")
    public Result insertBatch(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Device> devices = reader.readAll(Device.class);
        log.info("批量添加实验室：{}",devices);
        try {
            deviceService.insertBatch(devices);
        } catch (Exception e) {
            return Result.error("数据库批量导入出错！");
        }

        return Result.success();

    }

}
